﻿using System.ComponentModel;
using System.Diagnostics;
using System.IO.Compression;

namespace HostRestartManager;

#nullable disable
public class Helpers
{
    public static void ExecuteExternalProcess(string command, string arguments,string workingDirectory)
    {
        // 创建一个新的进程对象
        Process process = new Process();

        try
        {
            // 设置进程启动信息
            process.StartInfo.FileName = command;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false; // 不使用操作系统外壳程序启动
            process.StartInfo.WorkingDirectory = workingDirectory; 
            //process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出，如果需要获取外部程序的输出

            process.Start(); // 启动进程

        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        finally
        {
            process.Dispose(); // 释放资源
        }
    }

    public static void CopyFiles(string sourceFolder, string destFolder, string application)
    {
        LoadAndExecuteAllNupkgFiles(sourceFolder, destFolder);
    }

    public static void LoadAndExecuteAllNupkgFiles(string directoryPath, string extractPath)
    {
        // 获取所有模块的 .nupkg 文件路径
        string[] nupkgFiles = Directory.GetFiles(directoryPath, "*.nupkg");

        foreach (string nupkgFile in nupkgFiles.Where(x => !x.Contains("AiBLSmartEdu.Module.")))
        {
            LoadAndExecuteDll(nupkgFile, extractPath);
        }
    }

    public static void LoadAndExecuteDll(string packagePath, string extractPath)
    {
        // 解压 NuGet 包并获取解压后的目录
        string tempDir = ExtractPackage(packagePath, extractPath);

        string[] allFiles = Directory.GetFiles(tempDir, "*.*", SearchOption.AllDirectories);

        foreach (string file in allFiles)
        {
            if (IsIgnoreNugetFile(file)) continue;

            try
            {
                string sourceFile = file;
                string destinationFile = Path.Combine(extractPath, Path.GetFileName(file));
                // 如果目标文件已经存在，则先删除
                if (File.Exists(destinationFile))
                {
                    File.Delete(destinationFile);
                }
                File.Move(file, Path.Combine(extractPath, Path.GetFileName(file)));
                Console.WriteLine($"加载程序集成功: {file}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未能加载程序集: {file}");
                Console.WriteLine($"错误: {ex.Message}");
            }
        }

        Directory.Delete(tempDir, true);
    }

    public static string ExtractPackage(string packagePath, string extractPath)
    {
        // 创建一个临时目录来解压缩
        string tempDir = Path.Combine(extractPath, Path.GetRandomFileName());
        Directory.CreateDirectory(tempDir);

        // 解压缩 NuGet 包
        ZipFile.ExtractToDirectory(packagePath, tempDir);

        return tempDir;
    }

    public static bool IsProcessRunning(string processFileName)
    {
        try
        {
            Process[] processes = Process.GetProcesses();

            foreach (Process process in processes.Where(x => x.ProcessName == processFileName))
            {
                try
                {
                    if (!string.IsNullOrEmpty(process.MainModule.FileName) &&
                        process.MainModule.FileName.IndexOf(processFileName, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        return true;
                    }
                }
                catch (Exception ex) when (ex is Win32Exception || ex is InvalidOperationException)
                {
                    // 处理特定异常，如权限问题或进程已结束等
                    Console.WriteLine($"检查错误 {process.ProcessName}: {ex.Message}");
                }
            }
        }
        catch (Exception ex)
        {
            // 捕获其它可能的异常，如进程列表获取失败等
            Console.WriteLine($"获取错误：: {ex.Message}");
        }

        return false;
    }

    #region 私有方法
    private static bool IsIgnoreNugetFile(string filePath)
    {
        string[] fileNamesSuffix = @"^].xml|^.psmdcp|^.nuspec|^.rels".Replace("^", "").Split("|");
        foreach (string item in fileNamesSuffix)
        {
            if (filePath.EndsWith(item, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
        }
        return false;
    }
    #endregion
}
